package com.jiazixuan.stock.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiazixuan.stock.mapper.SysPermissionMapper;
import com.jiazixuan.stock.mapper.SysRoleMapper;
import com.jiazixuan.stock.mapper.SysRolePermissionMapper;
import com.jiazixuan.stock.mapper.SysUserRoleMapper;
import com.jiazixuan.stock.pojo.domain.MenusPermDomain;
import com.jiazixuan.stock.pojo.entity.SysPermission;
import com.jiazixuan.stock.pojo.entity.SysRole;
import com.jiazixuan.stock.pojo.entity.SysRolePermission;
import com.jiazixuan.stock.pojo.entity.SysUserRole;
import com.jiazixuan.stock.service.RoleService;
import com.jiazixuan.stock.utils.IdWorker;
import com.jiazixuan.stock.vo.req.AddRolesAndPermsReqVo;
import com.jiazixuan.stock.vo.req.UpdatePermsByRoleIdReqVo;
import com.jiazixuan.stock.vo.req.UserRolesReqVo;
import com.jiazixuan.stock.vo.resp.PageResult;
import com.jiazixuan.stock.vo.resp.R;
import com.jiazixuan.stock.vo.resp.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;
    /**
     * 获取用户具有的角色信息，以及所有角色信息
     */
    @Override
    public R<Map<String, Object>> getUserInfomation(String userId) {
        //根据传来的用户id获取角色id集合
        List<String> roleId = sysUserRoleMapper.getOwnRoleIdByUserId(userId);
        //获取所有角色信息
        List<SysRole> infos = sysRoleMapper.getAllRoles();
        //组装数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("ownRoleIds",roleId);
        map.put("allRole",infos);
        return R.ok(map);
    }



    /**
     * 更新角色信息
     * @return
     */
    @Override
    public R updateUserRoles(UserRolesReqVo userRoles) {
        //1.获取用户的id
        Long userId = userRoles.getUserId();
        //获取传来的角色id
        List<Long> roleIds = userRoles.getRoleIds();
        //获取已有的角色
        List<Long> existingRoleIds = sysUserRoleMapper.getRoleIdByUserId(userId);
        List<Long> rolesToDelete  = existingRoleIds.stream()
                .filter(roleId -> !roleIds.contains(roleId))
                .collect(Collectors.toList());
        //2.2查出需要增加哪些角色
        List<Long> rolesToAdd = roleIds.stream()
                .filter(ids -> !existingRoleIds.contains(ids))
                .collect(Collectors.toList());
        //3.执行删除和添加
        //3.1删除多余的角色
        if (!rolesToDelete.isEmpty()) {
            int count = sysUserRoleMapper.deleteRoles(userId,rolesToDelete);
            if(count<=0){
                return R.error(ResponseCode.ERROR);
            }
        }
        //3.2添加没有的角色
        if (!rolesToAdd.isEmpty()) {
            List<SysUserRole> newRelations = rolesToAdd.stream()
                    .map(roleId -> SysUserRole.builder()
                            .id(idWorker.nextId())
                            .userId(userId)
                            .roleId(roleId)
                            .build())
                    .collect(Collectors.toList());
            int count = sysUserRoleMapper.addRoles(newRelations);
            if(count<=0){
                return R.error(ResponseCode.ERROR);
            }
        }
        return R.ok();
    }

    /**
     * 查询当前所有角色信息
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R<PageResult<SysRole>> getRoles(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        //调用mapper接口
        List<SysRole> allRoles = sysRoleMapper.getAllRoles();
        if (CollectionUtils.isEmpty(allRoles)) {
            return R.error(ResponseCode.DATA_ERROR);
        }
        PageInfo<SysRole> rolePageInfo = new PageInfo<>(allRoles);
        PageResult<SysRole> result = new PageResult<>(rolePageInfo);
        return R.ok(result);
    }

    @Override
    public R<List<MenusPermDomain>> getMenusPermissions() {
        //查找所有的权限
        List<SysPermission> permissions = sysPermissionMapper.getAllPermission();
        //通过递归构造权限树
        List<MenusPermDomain> digui = MenusPermDomain.digui2(permissions, 0l);
        System.out.println("digui = " + digui);
        return R.ok(digui);
    }

    /**
     * 添加角色和角色关联权限(添加角色权限功能实现)
     */
    @Override
    @Transactional
    public R addRoleAndRolePermission(AddRolesAndPermsReqVo vo) {
        //添加角色
        SysRole role = SysRole.builder().id(idWorker.nextId()).name(vo.getName()).description(vo.getDescription()).build();
        int count = sysRoleMapper.addRole(role);
        //添加角色权限
        if (count>0) {
            //创建角色权限对象集合
            ArrayList<SysRolePermission> list = new ArrayList<>();
            //遍历权限id集合创建权限对象
            for (Long permissionsId : vo.getPermissionsIds()) {
                list.add(SysRolePermission.builder().id(idWorker.nextId()).roleId(role.getId()).permissionId(permissionsId).build());
            }
            //添加角色权限关联
            int i = sysRolePermissionMapper.addRolePermission(list);
            if(i>0){
                return R.ok();
            }
        }
            return R.error(ResponseCode.DATA_ERROR);
    }

    /**
     * 根据角色id查找对应的权限（点击角色编辑弹窗）
     */
    @Override
    public R<List<String>> getPermsByRoleId(String roleId) {
        //根据角色id获取所有的权限id

        List<Long> infos = sysRolePermissionMapper.selectPermissionByRoleId(roleId);

        System.out.println("infos = " + infos);
        //将所有info转化为String格式
        List<String> result = infos.stream().map(String::valueOf).collect(Collectors.toList());
        System.out.println("result = " + result);
        return R.ok(result);
    }

    /**
     * 更新角色信息，包含角色关联的权限信息（完成角色编辑）
     */
    @Override
    public R updateRoleAndPermission(UpdatePermsByRoleIdReqVo vo) {
        //获取传来的角色id
        Long id = vo.getId();
        //根据该角色id查询该角色信息判断是否要修改信息
        SysRole sysRole = sysRoleMapper.selectByPrimaryKey(id);
        if(!sysRole.getName().equals(vo.getName())){
            //修改角色名称
            int count = sysRoleMapper.updateRoleName(id,vo.getName());
        }
        if(!sysRole.getDescription().equals(vo.getDescription())){
            int count = sysRoleMapper.updateRoleDescription(id,vo.getDescription());
        }
        //查询该角色现在已经有的权限
        List<Long> exitPermissions = sysRolePermissionMapper.selectPermissionByRoleId(String.valueOf(id));
        //获取传来的权限id
        List<Long> permissionsIds = vo.getPermissionsIds();
        //查出需要删除哪些权限
        List<Long> permissionsToDelete = exitPermissions.stream()
                .filter(exitId -> !exitPermissions.contains(permissionsIds))
                .collect(Collectors.toList());
        //查出需要增加哪些权限
        List<Long> permissionsToAdd = permissionsIds.stream()
                .filter(permIds -> !permissionsIds.contains(exitPermissions))
                .collect(Collectors.toList());
        //执行删除和添加操作
        int i = sysRolePermissionMapper.deletePerByRoleIdAndPerId(id,permissionsToDelete);
        if (i<=0) {
            return R.error();
        }
        if (!permissionsToAdd.isEmpty()) {
            List<SysRolePermission> list = permissionsToAdd.stream()
                    .map(permissionsId -> SysRolePermission.builder()
                            .id(idWorker.nextId())
                            .roleId(id)
                            .permissionId(permissionsId)
                            .build())
                    .collect(Collectors.toList());
            int j = sysRolePermissionMapper.addRolePermission(list);
            if (j<=0) {
                return R.error();
            }
        }
        return R.ok();
    }

    /**
     * 删除角色信息
     * @param roleId
     * @return
     */
    @Override
    public R deleteRole(String roleId) {
        int i = sysRoleMapper.deleteByPrimaryKey(Long.parseLong(roleId));
        if (i>0) {
            return R.ok();
        }else{
            return R.error();
        }
    }

    /**
     * 更新用户的状态信息
     */
    @Override
    public R updateStatus(String roleId, Integer status) {
        int i = sysRoleMapper.updateStatusByRoleId(roleId,status);
        if (i>0) {
            return R.ok();
        }else{
            return R.error();
        }
    }
}
